package com.lanou.dllo.findfood.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.lanou.dllo.findfood.R;

/**
 * Created by dllo on 15/11/10.
 * 版本更新
 */
public class UpdateManger {


    private Context mContext;

    String Url;
    private String updateMsg = "有新版本更新,点击下载吧!";

//在这里接收传来的字符串

//自己的APK网址

    //这里是传过来的网址



    private Dialog noticeDialog;

    private Dialog downloadDialog;

    //保存到sd卡的路径
    private static final String savePath = "/sdcard/updatMyApp/";

    //文件保存的姓名
    private static final String saveFileName = savePath + "UpdateShishanglife.apk";


    private ProgressBar mProgress;


    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;

    private int progress;

    private Thread downLoadThread;

    private boolean interceptFlag = false;//下载完毕的标志




    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE://下载时调用
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:

                    installApk();
                    break;
                default:
                    break;
            }
        };
    };

    public UpdateManger(Context context, String url) {
        this.mContext = context;
        Url = url;
    }


    public void checkUpdateInfo(){
        showNoticeDialog();
    }


    private void showNoticeDialog(){
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("下载");
        builder.setMessage(updateMsg);
        builder.setPositiveButton("确定", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showDownloadDialog();
            }
        });
        builder.setNegativeButton("稍后再说", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
    }

    private void showDownloadDialog(){
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("下载");

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.progress, null);
        builder.setMessage("正在加载,请稍后O(∩_∩)");
        //将进度条加到对话框里面
        mProgress = (ProgressBar)v.findViewById(R.id.progress);
        builder.setView(v);
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();

        downloadApk();
    }

    public Runnable mdownApkRunnable = new Runnable() {

        //发送线程下载HttpURLConnection
        @Override
        public void run() {
            try {//
                URL url = new URL(Url);

                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                //// 调用HttpURLConnection连接对象的getInputStream()函数,
              // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
                InputStream is = conn.getInputStream();
// 现在通过输出流对象构建对象输出流对象，以实现输出可序列化的对象。
                File file = new File(savePath);//文件路径
                if(!file.exists()){//如果文件存在
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do{
                    int numread = is.read(buf);
                    count += numread;
                    progress =(int)(((float)count / length) * 100);

                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if(numread <= 0){

                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf,0,numread);
                }while(!interceptFlag);


                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch(IOException e){
                e.printStackTrace();
            }

        }
    };


    /**
     *
     * @param url
     */
//此方法下载APK
    private void downloadApk(){
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();//开启下载的线程
    }
    /**
     *
     * @param url
     */
    private void installApk(){
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        //用于显示用户的数据。
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);

    }
}
